using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BodySwing : MonoBehaviour
{
    public float force = 5f;

    private Rigidbody2D _rdbody;
    private Vector2 _input;


    // Start is called before the first frame update
    void Start()
    {
        _rdbody = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        _input = Vector2.zero;
        if (Input.GetKey(KeyCode.A))
        {
            //body.AddForce(Vector2.left * force);
            //_rdbody.velocity = Vector2.left * force;
            SetHorizontalVelocity(Vector2.left * force);

        }
        if (Input.GetKey(KeyCode.D))
        {
            //body.AddForce(Vector2.right * force);
            //_rdbody.velocity = Vector2.right * force;
            SetHorizontalVelocity(Vector2.right * force);
        }
    }

    private void FixedUpdate()
    {
        Vector3 velocity = _rdbody.velocity;
        if (_input.x != 0f)
            velocity.x = _input.x;
        _rdbody.velocity = velocity;
        //if (_input.x != 0f)
        //    _rdbody.AddForce(_input);
    }

    private void SetHorizontalVelocity(Vector2 velocity)
    {
        //Vector3 before = _rdbody.velocity;
        //before.x = velocity.x;
        //_rdbody.velocity = before;
        _input = velocity;
    }
}
